<template>
  <div id="root" class="app-wrapper"></div>
</template>

<script setup>
import { ref, onMounted } from "vue";

// 添加一个状态跟踪 Amis 是否加载完成
const amisLoaded = ref(false);

onMounted(() => {
  loadExternalResources();
});

// 动态加载 Amis 和其他资源
const loadExternalResources = () => {
  // 先加载 Vue，因为 Amis 可能依赖 Vue
  const scriptVue = document.createElement("script");
  scriptVue.src = "https://unpkg.com/vue@3";
  scriptVue.onload = () => {
    console.log("Vue 加载完成");

    // Vue 加载完成后再加载 Amis
    const scriptAmis = document.createElement("script");
    scriptAmis.src = "https://unpkg.com/amis@6.13.0/sdk/sdk.js";
    scriptAmis.onload = () => {
      console.log("Amis SDK 加载完成");
      amisLoaded.value = true;
      // Amis 加载完成后再获取菜单列表
      getMenusList();
    };
    document.body.appendChild(scriptAmis);
  };
  document.body.appendChild(scriptVue);

  // 加载 History
  const scriptHistory = document.createElement("script");
  scriptHistory.src = "https://unpkg.com/history@4.10.1/umd/history.js";
  scriptHistory.onload = () => {
    console.log("History 加载完成");
  };
  document.body.appendChild(scriptHistory);

  // 动态加载 CSS
  const linkAntd = document.createElement("link");
  linkAntd.rel = "stylesheet";
  linkAntd.href = "https://unpkg.com/amis@6.13.0/sdk/antd.css";
  document.head.appendChild(linkAntd);

  const linkHelper = document.createElement("link");
  linkHelper.rel = "stylesheet";
  linkHelper.href = "https://unpkg.com/amis@6.13.0/sdk/helper.css";
  document.head.appendChild(linkHelper);

  const linkIconFont = document.createElement("link");
  linkIconFont.rel = "stylesheet";
  linkIconFont.href = "https://unpkg.com/amis@6.13.0/sdk/iconfont.css";
  document.head.appendChild(linkIconFont);
};

const getMenusList = () => {
  const token = localStorage.getItem("token");
  if (!token) {
    window.location.href = "/admin";
    return;
  }

  Meteor.call("getMenusList", token, (err, res) => {
    if (err) {
      console.error("调用错误:", err.message);
      window.location.href = "/admin";
    } else {
      console.log("调用成功:", res);
      // 确保 Amis 已加载再初始化
      if (amisLoaded.value) {
        initAmisApp(res);
      } else {
        // 如果还没加载完成，等待加载完成后再初始化
        const checkLoaded = setInterval(() => {
          if (amisLoaded.value) {
            clearInterval(checkLoaded);
            initAmisApp(res);
          }
        }, 100);
      }
    }
  });
};

function initAmisApp(res) {
  // 现在可以安全地使用 amisRequire 了
  const amis = amisRequire("amis/embed");
  const match = amisRequire("path-to-regexp").match;
  const history = History.createHashHistory();
  const app = res;

  // ... 其余代码保持不变 ...
  const normalizeLink = (to, location = history.location) => {
    if (!to) return "";

    if (to[0] === "#") to = location.pathname + location.search + to;
    else if (to[0] === "?") to = location.pathname + to;

    const [pathname = "", search = "", hash = ""] = [
      to.split(/[?#]/)[0],
      to.includes("?")
        ? to.slice(
            to.indexOf("?"),
            to.includes("#") ? to.indexOf("#") : undefined
          )
        : "",
      to.includes("#") ? to.slice(to.indexOf("#")) : location.hash,
    ];

    return pathname + search + hash;
  };

  const isCurrentUrl = (to, ctx) => {
    const pathname = history.location.pathname;
    const link = normalizeLink(to, { ...location, pathname, hash: "" });

    if (!~link.indexOf("http") && ~link.indexOf(":")) {
      return match(link, {
        decode: decodeURIComponent,
        strict: ctx?.strict ?? true,
      })(pathname);
    }
    return decodeURI(pathname) === link;
  };

  const amisInstance = amis.embed(
    "#root",
    app,
    {
      location: history.location,
    },
    {
      requestAdaptor: (api) => {
        api.headers["Authorization"] =
          "Bearer " + localStorage.getItem("token") || [];
        console.log("全局请求适配器", api);
        return api;
      },
      responseAdaptor: (api, payload, query, request, response) => {
        if (response.status === 401) {
          window.location.href = "/admin";
        }
        return payload;
      },
      updateLocation: (location, replace) => {
        location = normalizeLink(location);
        if (location === "goBack") return history.goBack();
        if (location === history.location.pathname + history.location.search)
          return;
        if (/^https?:\/\//.test(location))
          return (window.location.href = location);
        history[replace ? "replace" : "push"](location);
      },
      jumpTo: (to, action) => {
        to = normalizeLink(to);
        if (isCurrentUrl(to)) return;
        if (action?.actionType === "url") {
          return action.blank === false
            ? (window.location.href = to)
            : window.open(to, "_blank");
        }
        if (action?.blank) return window.open(to, "_blank");
        if (/^https?:\/\//.test(to)) return (window.location.href = to);
        history.push(to);
      },
      isCurrentUrl,
      theme: "antd",
    }
  );

  history.listen((state) => {
    amisInstance.updateProps({ location: state.location || state });
  });
}
</script>

<style>
html,
body,
.app-wrapper {
  position: relative;
  width: 100%;
  height: 100%;
  margin: 0;
  padding: 0;
}
</style>
